package com.example.mail.service;

import com.example.common.pojo.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;
import java.util.Date;

@Service
@Slf4j
public class MailService {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private MailProperties mailProperties;
    @Autowired
    private TemplateEngine templateEngine;

    public void sendEmp(Employee employee)throws Exception{
        MimeMessage mimeMailMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMailMessage);

        helper.setFrom(mailProperties.getUsername());
        helper.setTo(employee.getEmail());
        helper.setSubject("入职欢迎邮件");
        helper.setSentDate(new Date());


        Context context = new Context();
        context.setVariable("name",employee.getName());
        context.setVariable("password",employee.getPosition().getName());

        String mail = templateEngine.process("main", context);
        helper.setText(mail,true);
        javaMailSender.send(mimeMailMessage);
    }
}
